//
//  YURecommendViewController.m
//  百思不得
//
//  Created by 宋禹奇 on 15/9/4.
//  Copyright (c) 2015年 宋禹奇. All rights reserved.
//

#import "YURecommendViewController.h"
#import <AFNetworking.h>
#import <SVProgressHUD.h>
#import "YURecommendCategoryCell.h"
#import "YURecommendCategory.h"
#import <MJExtension.h>
#import "YURecommendUserCell.h"
#import "YURecommendUser.h"
#import <MJRefresh.h>

#define YUSelectedCategory self.categories[self.categoryTableView.indexPathForSelectedRow.row]

@interface YURecommendViewController ()<UITableViewDataSource,UITableViewDelegate>
//左边数据
@property (nonatomic, strong) NSArray *categories;
//右边数据
//@property (nonatomic, strong) NSArray *users;
//左边表格
@property (weak, nonatomic) IBOutlet UITableView *categoryTableView;
//右边表格
@property (weak, nonatomic) IBOutlet UITableView *userTableView;
//请求参数
@property (nonatomic, strong) NSMutableDictionary *params;
//AFN请求管理者
@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation YURecommendViewController

static NSString * const YUCategoryId = @"category";
static NSString * const YUUserId = @"user";
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //控件的初始化
    [self setupTableView];
  
    //添加刷新控件
    [self setupRefresh];
    
    //添加左侧数据
    [self loadCategories];
}

- (void)loadCategories{
    //显示指示器
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
    
    //发送请求
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        //隐藏指示器
        [SVProgressHUD dismiss];
        
        //服务器返回的JSON数据<MJExtension.h>
        self.categories = [YURecommendCategory objectArrayWithKeyValuesArray:responseObject[@"list"]];
        //YULog(@"%@",self.categories);
        //刷新表格
        [self.categoryTableView reloadData];
        
        [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        
        //让用户表格进入下拉刷新状态
        [self.userTableView.header beginRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //显示失败信息
        [SVProgressHUD showErrorWithStatus:@"加载推荐信息失败!"];
    }];
    

}

- (void)setupTableView{
    //注册
    [self.categoryTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YURecommendCategoryCell class]) bundle:nil] forCellReuseIdentifier:YUCategoryId];
    [self.userTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YURecommendUserCell class]) bundle:nil] forCellReuseIdentifier:YUUserId];
    
    //设置inset
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.categoryTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.userTableView.contentInset = self.categoryTableView.contentInset;
    self.userTableView.rowHeight = 70;
    
    self.categoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.userTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.title = @"推荐关注";
    
    //设置背景颜色
    self.view.backgroundColor = YUGlobalBg;
    

}
//添加刷新控件
- (void)setupRefresh{
    self.userTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    self.userTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
    self.userTableView.footer.hidden = YES;
}
//加载用户数据
- (void)loadNewUsers{
    YURecommendCategory *rc = YUSelectedCategory;
    //设置当前页码为1;
    rc.currentPage = 1;
    
    //请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = @(rc.id);
    params[@"page"] = @(rc.currentPage);
    self.params = params;
    
    //发送请求给服务器,加载右侧的数据
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        //字典数组变模型数组
        NSArray *users = [YURecommendUser objectArrayWithKeyValuesArray:responseObject[@"list"]];
        //清除所有旧数组
        [rc.users removeAllObjects];
        //添加当前类别对应的用户数组中
        [rc.users addObjectsFromArray:users];
        //保存总数
        rc.total = [responseObject[@"total"] integerValue];
        //不是最后一次请求
        if (self.params != params) {
            return ;
        }
        //刷新右侧表格
        [self.userTableView reloadData];
        //结束刷新
        [self.userTableView.header endRefreshing];
        
        //让底部控件结束刷新
        [self checFooterState];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.params != params) {
            return ;
        }
        //提醒
        [SVProgressHUD showWithStatus:@"加载用户数据失败!"];
        //结束刷新
        [self.userTableView.header endRefreshing];
    }];

}
//加载更多用户
- (void)loadMoreUsers{
    YURecommendCategory *category = YUSelectedCategory;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = @(category.id);
    params[@"page"] = @(++category.currentPage);
    self.params = params;
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSArray *users = [YURecommendUser objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [category.users addObjectsFromArray:users];
        
        if (self.params != params) {
            return ;
        }
        
        [self.userTableView reloadData];
        
        [self checFooterState];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.params != params) {
            return ;
        }
        
        [SVProgressHUD showErrorWithStatus:@"加载用户数据失败!"];
        
        [self.userTableView.footer endRefreshing];
    }];
}
//时刻监听footer的状态
- (void)checFooterState{
    YURecommendCategory *rc = YUSelectedCategory;
    
    self.userTableView.footer.hidden = (rc.users.count == 0);
    
    if (rc.users.count == rc.total) {
        [self.userTableView.footer noticeNoMoreData];
    } else {
        [self.userTableView.footer endRefreshing];
    }
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.categoryTableView) {
        return self.categories.count;
    }
    [self checFooterState];
    
    return [YUSelectedCategory users].count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.categoryTableView) {
        YURecommendCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:YUCategoryId];
        cell.category = self.categories[indexPath.row];
        return cell;

    } else {
        YURecommendUserCell *cell = [tableView dequeueReusableCellWithIdentifier:YUUserId];

        cell.user = [YUSelectedCategory users][indexPath.row];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.userTableView.header endRefreshing];
    [self.userTableView.footer endRefreshing];
    
    YURecommendCategory *c = self.categories[indexPath.row];
    
    if (c.users.count) {
        // 显示曾经的数据
        [self.userTableView reloadData];
    } else {
        [self.userTableView reloadData];
        
        [self.userTableView.header beginRefreshing];
    }

}

- (void)dealloc{
    //停止所有操作
    [self.manager.operationQueue cancelAllOperations];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
